libname a "D:\SAS\Dataset\Compustat\Compustat US";

data a (keep=fyear cusip sale ni XSGA  SIC AT) ;
set a.Compustat1950_1979 a.Compustat1980_1989 a.Compustat1990_1995 a.Compustat1996_2000 a.Compustat2001_2005 a.Compustat2006_2010 a.Compustat2011_2020 a.Compustat2021_2023;
run;

proc sort data=a; by cusip fyear;

data a1;
set a; by cusip fyear;
sale1= lag (sale);
if first.cusip then sale1=.;
at1=log(at);
if first.cusip then at1=.;
run;

data a1;
set a1;
if sale<sale1 then saledecrease=1; else saledecrease=0;
if ni< 0 then loss=1; else loss=0;
saled=sale/((at+at1)/2);
sga=xsga/((at+at1)/2);
sic1=substr (sic, 1, 3);
run;


proc sort data=a1; by fyear sic1; run; 

proc reg data=a1 noprint tableout outest=a2; by fyear sic1;
model sga = saled saledecrease loss; 
run;


data a2 (keep=fyear sic1 intercept saled loss saledecrease) ;
set a2; where sga^=.;
run;


data a2 (rename=(saled=saledc  loss=lossc  saledecrease =saledecreasec));
set a2;
run;


proc sort data=a1; by fyear sic1;
proc sort data=a2; by fyear sic1;

data a3;
merge a1 a2; by fyear sic1;
run;


data a4;
set a3;
mainsga=intercept+saled*saledc + loss*lossc + saledecrease *saledecreasec;
run;

data a4;
set a4;
sgain=sga-mainsga;
run;


data a4;
set a4;
sgaintangible= sgain*((at+at1)/2);
run;


libname s "D:\SAS\Project\Persistence of MTB Ratio";

data s.sgaintangible;
set a4;
run;
